import './index.scss';
import treeHtml from './index.html';
import app from '../../index.js';
import * as d3 from 'd3';

export default{
  init:function () {
    app.config(['$stateProvider', function ($stateProvider) {
      $stateProvider.state('demo1', {
        url: '/demo1',
        template: treeHtml
      });
    }]);
    app.controller('demo1Controller', ["$scope","$http",function ($scope,$http) {
        $http.get('/api/data').then(function (d) {
            var treeData = d.data;
            var circleData = treeData.data.ciNodes;
            function categoricalSplit() {

                var catScale = d3.scalePoint()
                    .domain(circleData.map(function(d) { return d['className']; }))
                    .range([0, width])
                    .padding(0.5);

                var labels = svg.selectAll("text")
                    .data(catScale.domain())
                    .enter().append("text")
                    .attr("class", "label")
                    .text(function(d) {return d; })
                    .attr("fill", "#DDD")
                    .attr("text-anchor", "middle")
                    .attr("x", function(d) { return catScale(d); })
                    // .attr("y", height / 2.0 - 100);
                    .attr("y",  100);

                var xCatForce = d3.forceX(function(d) {
                    return catScale(d['className']);
                });

                var splitState = false;
                document.getElementById("split-button").onclick = function() {
                    if(!splitState) {
                        simulation.force("x", xCatForce);
                        labels.attr("fill", "#000");
                    } else {
                        simulation.force("x", centerXForce);
                        labels.attr("fill", "#DDD");
                    }

                    splitState = !splitState;

                    simulation.alpha(1).restart();
                };
            }
            var svg = d3.select("svg"),
                width = +svg.attr("width"),
                height = +svg.attr("height");

            var chargeForce = d3.forceManyBody()

            var centerXForce = d3.forceX(width / 2);

            var centerYForce = d3.forceY(350);

            var simulation = d3.forceSimulation()
                .force("charge", chargeForce)
                .force("x", centerXForce)
                .force("y", centerYForce);

            var node = svg.selectAll("circle")
                .data(circleData)
                .enter().append("circle")
                .attr("r", 10)
                .attr("fill", function(d){return d.classColor});

            simulation.nodes(circleData)
                .on("tick", function() {
                    node.attr("cx", function(d) { return d.x; })
                        .attr("cy", function(d) { return d.y; });
                });
            categoricalSplit();
        })
    }]);
  }

}

